package com.confinderence;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.confinderence.ConferencesTableFragment.IProvider;
import com.confinderence.WebServiceTask.IResponseHandler;
import com.confinderence.model.Conference;
import com.confinderence.utils.gson.ArrayAdapterFactory;
import com.confinderence.utils.gson.CustomDateTypeAdapter;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;

public class ConferenceActivity extends Activity implements IProvider {
	private WebServiceTask mTask;
	private List<Conference> mConferences;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_conference);
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, new ConferencesTableFragment(this, this)).commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.logged_in_menu, menu);
		Utils.initMenu(menu, this);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	private void setTable(TableLayout tl) {
		for (int i = 0; i < mConferences.size(); i++) {
			final Conference conf = mConferences.get(i);
			TableRow tr = new TableRow(this);
			addCell(tr, conf.getName(), 0.2f);
			addCell(tr, conf.getLocation(), 0.2f);
			addCell(tr, conf.getStartTime().toString(), 0.3f);
			addCell(tr, conf.getEndTime().toString(), 0.3f);

			tr.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					goToConferenceDetails(conf);
				}
			});
			tr.setBackgroundColor(i % 2 == 0 ? 0xFF8C89D6 : 0xFFCECED6);
			tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
					LayoutParams.WRAP_CONTENT));
		}
		tl.setBackground(getResources().getDrawable(R.drawable.layout_border));
		// tl.setColumnShrinkable(2, false);
		// tl.setColumnShrinkable(3, false);
		tl.requestLayout();
	}

	public void addCell(TableRow tr, String text, float weight) {
		TextView tv = new TextView(this);
		tv.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, weight));
		tv.setText(text);
		tv.setPadding(10, 5, 10, 5);
		tv.setTextSize(20);
		tv.setGravity(Gravity.CENTER);
		tr.addView(tv);
	}
	@Override
	public void initTable(final TableLayout tl) {
		mTask = new WebServiceTask(WebServiceTask.GET_TASK, this, getString(R.string.wait_msg),
				new IResponseHandler() {

					@Override
					public void handleResponse(String response) {
						Gson gson = new GsonBuilder()
								.registerTypeAdapter(Date.class, new CustomDateTypeAdapter())
								.registerTypeAdapterFactory(new ArrayAdapterFactory())
								.setPrettyPrinting().create();
						try {
							JSONObject json = new JSONObject(response);
							JSONArray array = json.getJSONArray("conference");
							Type collectionType = new TypeToken<Collection<Conference>>() {
							}.getType();
							mConferences = gson.fromJson(array.toString(), collectionType);
							// response = Utils.cleanDateFormat(response);
							setTable(tl);

						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				});
		mTask.execute(ConferencesTableFragment.URL);
	}

	protected void goToConferenceDetails(Conference conference) {
		getFragmentManager().beginTransaction()
				.replace(R.id.container, new ConferenceDetailsFragment(this, conference)).commit();
	}
}
